﻿DECLARE @StatDate datetime
DECLARE @Counter int
SET @Counter = 254

WHILE (@Counter > 250)
 BEGIN
   SET @StatDate = DATEADD(D, 0, DATEDIFF(D, @Counter, GETDATE()))
   INSERT INTO Table1 (Field1, Field2) 
     VALUES 
     (SELECT
          @StatDate AS day_stat,
          md.to_abonent_id AS ap_id,
          count(md.hostname_id) AS msg_cnt,
          sum(md.msg_size) AS msg_size
        FROM mon400_data md
        WHERE
          (md.datetime_in BETWEEN (@StatDate) AND (@StatDate + 1)) and
          ((md.msg_kind = 0) /*or (md.msg_kind = 2)*/) AND   /* только входящие письма от АП */
          (md.msg_cirkul = 0)  /* уберем лишние циркуляры */
        GROUP BY md.to_abonent_id)
   SET @Counter = @Counter - 1
 END



